<template>
  <el-form-item label="所属机构">
    <el-cascader
      ref="insCascader"
      v-model="selectedIns"
      :props="_cascaderProps"
      :options="insTree"
      clearable
      v-bind="$attrs"
      @change="handleChange"
    />
  </el-form-item>
</template>

<script lang="ts" setup>
import { Ref } from "vue";
import { IInsTreeItem } from "@/api/modules/orgManage";
import { queryTree2 } from "@/api/orgManage";

const store = useStore()
const props = withDefaults(defineProps<{
  selected?: number[],
  cascaderProps?: {
    multiple?: boolean
  },
}>(), {
  selected: () => [],
  cascaderProps: () => ({
    multiple: true,
  })
})

const emits = defineEmits([ "change", "update:selected" ])
const insCascader = ref()


const getSelectedId = () => {
  return insCascader.value?.getCheckedNodes()
    .map((item:any) => item.data)
    .map((item:IInsTreeItem) => item.id)
}

const getSelected = () => {
  return insCascader.value?.getCheckedNodes()
    .map((item: any) => item.data)
}

const selectedIns = computed({
  get() {
    return props.selected
  },
  set(newValue) {
    // console.log('compu selected', newValue)
    emits("update:selected", newValue)
  }
})

const handleChange = () => {
  const checkedNodes = getSelectedId()
  // console.log('change', checkedNodes)
  emits("change", checkedNodes)
}

const _cascaderProps = ref({
  multiple: true,
  checkStrictly: true,
  value: 'id',
  label: 'name',
  ...props.cascaderProps,
})

const insTree: Ref<IInsTreeItem[]> = ref([])

const getInsTree = async () => {
  const rs = await queryTree2()

  if (rs.code === 200) {
    insTree.value = rs.payload ?? []
  }
}

onBeforeMount(() => {
  // selectedIns.value = [ store.state.user.insId ]
  // console.log('ins beforemount', selectedIns.value)
})

onMounted(async () => {
  // console.log('in mounted', selectedIns.value)
  await getInsTree()
})

defineExpose({
  getSelected
})
</script>

<style scoped lang="scss">
:deep(.icon-arrow-down:before) {
  display: none;
}
</style>
